package com.lzx.iteam.net;

import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import com.lzx.iteam.LoginActivity;
import com.lzx.iteam.R;
import com.lzx.iteam.TalkListActivity;
import com.lzx.iteam.bean.TalkListData;
import com.lzx.iteam.provider.CloudContactsDB;
import com.lzx.iteam.provider.CloudContactsDBHelper;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangshuai on 15/10/22.
 */
public class TalkListCenter {

    private static final String TAG = "get_talk_data";
    private static final int MSG_TALK_GETLIST = 1000;

    private ArrayList<TalkListData> mTalkListData = new ArrayList<TalkListData>();
    private TalkDataListener mListener;
    private CloudContactsDBHelper mHelper;
    private AllDialogUtil mDialogUtil;
    private static TalkListCenter sInstance;
    private Context mContext;
    private boolean isUpDate;
    private String mAction;
    private PreferenceUtil mPreferenceUtil;
    private String mSetUserId;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TALK_GETLIST:
                    if (msg.arg1 == 0) {
                        if (isUpDate) {
                            ArrayList<TalkListData> cloudTalkList = (ArrayList<TalkListData>) msg.obj;
                            if (cloudTalkList != null && cloudTalkList.size() > 0) {
                                mPreferenceUtil.save("talk_count", cloudTalkList.get(0).allCounts);
                            } else {
                                mPreferenceUtil.save("talk_count", "0");
                            }
                            ArrayList<TalkListData> localTalkList = new ArrayList<TalkListData>();
                            localTalkList.addAll(mTalkListData);
//                            Log.d(TAG,localTalkList.get(0).updateTime + " =bijiao  message== " + cloudTalkList.get(0).updateTime);
                            if (updateCloudTalkData(localTalkList, cloudTalkList)) {
                                mTalkListData.clear();
                                notifyCloudTalkUpdate();
                            } else {
                                if (mListener != null) mListener.onNoChange();
                            }
                        } else {
                            ArrayList<TalkListData> cloudTalkList = (ArrayList<TalkListData>) msg.obj;
                            for (int i = 0; i < cloudTalkList.size(); i++) {
                                insertTalkData(cloudTalkList.get(i));
                            }
                            notifyAddTalkList();
                        }

                    } else if (msg.arg1 == 1002 || msg.arg1 == 1003) {//其他接口也应该加此判断，当前其他接口未加
                        mDialogUtil.titleMsgBtnStyle("提示", (String) msg.obj, mContext.getString(R.string.ok));
                        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                            @Override
                            public void onConfirmClick(Dialog lDialog) {

                                lDialog.dismiss();
                                Intent intent = new Intent(mContext, LoginActivity.class);
                                mContext.startActivity(intent);
                                ((TalkListActivity) mContext).finish();

                            }

                            @Override
                            public void onCancelClick(Dialog lDialog) {
                            }
                        });
                    } else {
                        if (mListener != null) mListener.onError(msg.arg1, (String) msg.obj);
                    }
                    break;
            }

        }
    };

    private TalkListCenter(Context context) {
        mContext = context;
        mHelper = new CloudContactsDBHelper(mContext);
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);
        mDialogUtil = AllDialogUtil.getInstance((TalkListActivity) mContext);

    }

    public static TalkListCenter getInstance(Context c) {
        if (sInstance == null) {
            sInstance = new TalkListCenter(c);
        }
        return sInstance;
    }

    public interface TalkDataListener {
        void onChange(ArrayList<TalkListData> talkList);

        void onNoChange();

        void onAddMore(ArrayList<TalkListData> talkList);

        void onError(int errNum, String obj);
    }

    public void setUsetId(String userId) {
        this.mSetUserId = userId;
    }

    public void setUpdateTalkListener(TalkDataListener listener) {
        this.mListener = listener;
    }

    public ArrayList<TalkListData> getTalkData(int pageIndex, boolean update, String action) {
        this.isUpDate = update;
        this.mAction = action;
        mTalkListData.clear();
        mTalkListData = getLocalTalkData();
        /*if (mTalkListData.size() == 0){
            mTalkListData = getLocalTalkData();
//            Log.e(TAG, "get local data ========= " + mTalkListData.get(0).updateTime) ;
        }
        /*if(mTalkListData.size()==0||mTalkListData.size()!=Integer.parseInt(mPreferenceUtil.getString("talk_count","0"))){
            if(TalkListActivity.CONTACTS_CIRCLE.equals(mAction)){
                getCircleTalkData(pageIndex);
            }else if(TalkListActivity.MY_PERSONAL_SPACE.equals(mAction)){
                getMyTalkList(pageIndex);
            }
        }else if(mTalkListData.size()!=0||mTalkListData.size()==Integer.parseInt(mPreferenceUtil.getString("talk_count","0"))){
            ((TalkListActivity)mContext).setFooterText(true);
        }*/
        if (TalkListActivity.CONTACTS_CIRCLE.equals(mAction)) {
            getCircleTalkData(pageIndex);
        } else if (TalkListActivity.MY_PERSONAL_SPACE.equals(mAction) || TalkListActivity.OTHER_PERSONAL_SPACE.equals(mAction)) {
            getMyTalkList(pageIndex);
        }
        return mTalkListData;
    }

    private ArrayList<TalkListData> getLocalTalkData() {
        ArrayList<TalkListData> localData = new ArrayList<TalkListData>();
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = mHelper.getReadableDatabase();
            cursor = db.query(CloudContactsDB.TalkData.TABLE_NAME, null, "talk_action = ? ", new String[]{mAction}, null, null, CloudContactsDB.TalkData.TALK_CREATE_TIME + " desc");
            while (cursor.moveToNext()) {
                TalkListData talkListData = new TalkListData();
                talkListData.talkId = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_ID));
                talkListData.uId = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.USER_ID));
                talkListData.uName = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.USER_NAME));
                talkListData.uImage = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.USER_IMG));
                talkListData.text = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_TEXT));
                talkListData.contentType = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_CONTENT_TYPE));
                talkListData.contentKey = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_CONTENT_KEY));
                talkListData.thumbImage = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_THUMBIMAGE));
                talkListData.oriImage = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_ORIIMAGE));
                talkListData.updateTime = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_UPDATE_TIME));
                talkListData.createTime = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_CREATE_TIME));
                talkListData.isPraise = cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_ISPRAISE));
                talkListData.comments = (ArrayList<Map<String, String>>) StringUtil.objectWithString(cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_COMMENTS_LIST)));
                talkListData.praises = (ArrayList<Map<String, String>>) StringUtil.objectWithString(cursor.getString(cursor.getColumnIndex(CloudContactsDB.TalkData.TALK_PRAISES_LIST)));
                localData.add(talkListData);
            }
        } catch (Exception e) {
            Log.e(TAG, "findTalk  error" + e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return localData;
    }


    public synchronized long insertTalkData(TalkListData talkListData) {
        SQLiteDatabase db = null;
        long flag = 0l;
        ContentValues values = new ContentValues();
        try {
            if (getTalkCount(talkListData.talkId) == 0) {
                db = mHelper.getWritableDatabase();
                values.put(CloudContactsDB.TalkData.TALK_ID, talkListData.talkId);
                values.put(CloudContactsDB.TalkData.USER_ID, talkListData.uId);
                values.put(CloudContactsDB.TalkData.USER_NAME, talkListData.uName);
                values.put(CloudContactsDB.TalkData.USER_IMG, talkListData.uImage);
                values.put(CloudContactsDB.TalkData.TALK_TEXT, talkListData.text);
                values.put(CloudContactsDB.TalkData.TALK_THUMBIMAGE, talkListData.thumbImage);
                values.put(CloudContactsDB.TalkData.TALK_ORIIMAGE, talkListData.oriImage);
                values.put(CloudContactsDB.TalkData.TALK_UPDATE_TIME, talkListData.updateTime);
                values.put(CloudContactsDB.TalkData.TALK_CREATE_TIME, talkListData.createTime);
                values.put(CloudContactsDB.TalkData.TALK_COMMENTS, talkListData.talkComments);
                values.put(CloudContactsDB.TalkData.TALK_CONTENT_TYPE, talkListData.contentType);
                values.put(CloudContactsDB.TalkData.TALK_CONTENT_KEY, talkListData.contentKey);
                values.put(CloudContactsDB.TalkData.TALK_ISPRAISE, talkListData.isPraise);
                values.put(CloudContactsDB.TalkData.TALK_COMMENTS_LIST, StringUtil.stringWithObject(talkListData.comments));
                values.put(CloudContactsDB.TalkData.TALK_PRAISES_LIST, StringUtil.stringWithObject(talkListData.praises));
                values.put(CloudContactsDB.TalkData.TALK_ACTION, mAction);
                flag = db.insert(CloudContactsDB.TalkData.TABLE_NAME, null, values);
            }
        } catch (Exception e) {
            Log.e(TAG, "insert_error" + e.toString());
        } finally {
            db.close();
        }
        Log.i("Talk", "--insert_result--" + flag);
        return flag;
    }

    /**
     * @param action   true：点赞 false：评论
     * @param praise   点赞内容
     * @param comments 评论列表
     * @param talkId   talk_id
     * @return
     */
    public synchronized long upDateCloudTalkData(boolean action, String praise, ArrayList<Map<String, String>> comments, String talkId) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        long flag = 0l;
        ContentValues values = new ContentValues();
        if (action) {
            values.put(CloudContactsDB.TalkData.TALK_ISPRAISE, praise);
            values.put(CloudContactsDB.TalkData.TALK_PRAISES_LIST, StringUtil.stringWithObject(comments));
        } else {
            values.put(CloudContactsDB.TalkData.TALK_COMMENTS_LIST, StringUtil.stringWithObject(comments));
        }
        String whereClause = "talk_id = ? ";
        String[] whereArgs = {talkId};
        flag = db.update(CloudContactsDB.TalkData.TABLE_NAME, values, whereClause, whereArgs);
        Log.d("upda_tatalk", "修改结果" + flag + "talk_id=" + talkId);
        return flag;
    }

    public synchronized long updateCloudTalkData(String talkId, TalkListData talkListData) {
        SQLiteDatabase db = null;
        long flag = 0l;
        ContentValues values = new ContentValues();
        try {
            db = mHelper.getWritableDatabase();
            values.put(CloudContactsDB.TalkData.TALK_ID, talkListData.talkId);
            values.put(CloudContactsDB.TalkData.USER_ID, talkListData.uId);
            values.put(CloudContactsDB.TalkData.USER_NAME, talkListData.uName);
            values.put(CloudContactsDB.TalkData.USER_IMG, talkListData.uImage);
            values.put(CloudContactsDB.TalkData.TALK_TEXT, talkListData.text);
            values.put(CloudContactsDB.TalkData.TALK_THUMBIMAGE, talkListData.thumbImage);
            values.put(CloudContactsDB.TalkData.TALK_ORIIMAGE, talkListData.oriImage);
            values.put(CloudContactsDB.TalkData.TALK_UPDATE_TIME, talkListData.updateTime);
            values.put(CloudContactsDB.TalkData.TALK_CREATE_TIME, talkListData.createTime);
            values.put(CloudContactsDB.TalkData.TALK_COMMENTS, talkListData.talkComments);
            values.put(CloudContactsDB.TalkData.TALK_CONTENT_TYPE, talkListData.contentType);
            values.put(CloudContactsDB.TalkData.TALK_CONTENT_KEY, talkListData.contentKey);
            values.put(CloudContactsDB.TalkData.TALK_ISPRAISE, talkListData.isPraise);
            values.put(CloudContactsDB.TalkData.TALK_COMMENTS_LIST, StringUtil.stringWithObject(talkListData.comments));
            values.put(CloudContactsDB.TalkData.TALK_PRAISES_LIST, StringUtil.stringWithObject(talkListData.praises));
            flag = db.update(CloudContactsDB.TalkData.TABLE_NAME, values, " talk_id = ? ", new String[]{talkId});
        } catch (Exception e) {
            Log.e(TAG, "insert_error" + e.toString());
        } finally {
            db.close();
        }
        Log.i(TAG, "--insert_result--" + flag);
        return flag;
    }

    /**
     * 删除一个
     *
     * @param talkId
     * @return 非0表示成功，0表示失败
     */
    public int deleteTalkById(String talkId) {
        SQLiteDatabase db = null;
        int delete = 0;
        try {
            db = mHelper.getWritableDatabase();
            delete = db.delete(CloudContactsDB.TalkData.TABLE_NAME, " talk_id = ?", new String[]{talkId});
        } catch (SQLException e) {
            Log.e(TAG, " error deleteEventDraftsByEventId " + e);
        } finally {
            if (db != null) {
                db.close();
            }
        }
        Log.i("delete_drafts", delete + "删除");
        return delete;
    }

    /**
     * 删除符合条件的所有人脉圈
     *
     * @return 非0表示成功，0表示失败
     */
    public synchronized boolean deleteAllTalk(String action) {
        SQLiteDatabase db = mHelper.getWritableDatabase();
        int result = 0;
        try {
            result = db.delete(CloudContactsDB.TalkData.TABLE_NAME, "talk_action = ? ", new String[]{action});
            Log.e(TAG, "delete" + result);

        } catch (SQLException e) {
            Log.e(TAG, " error deleteAllTalk" + e);
        } finally {
            if (db != null) {
                db.close();
            }
        }
        return (result != 0);
    }

    private void deleteCloudTalkData(ArrayList<TalkListData> talkList) {
        if (talkList == null || talkList.size() == 0) {
            Log.w(TAG, "deleteCloudGroupItem with null group list.");
        }

        /*StringBuilder sb = new StringBuilder();
        sb.append( CloudContactsDB.TalkData.TALK_ID+ " IN (")
                .append(talkList.get(0).talkId);
        for (int i = 1; i < talkList.size(); i++) {
            sb.append(',').append(talkList.get(i).talkId);
        }
        sb.append(')');*/

        for (int i = 0; i < talkList.size(); i++) {
            deleteTalkById(talkList.get(i).talkId);
            Log.i(TAG, "--delete_ talk Id--" + talkList.get(i).talkId);
        }

    }

    private void getCircleTalkData(int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        String sid = LocalLogin.getInstance().mSid;
        if (sid.equals(LocalLogin.VISITOR_SID)){
            LocalLogin.getInstance().login(mContext);
            sid = LocalLogin.getInstance().mSid;
        }
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, sid));
        if (isUpDate) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));
        }
        GetTalkListMsg message = new GetTalkListMsg(mHandler.obtainMessage(MSG_TALK_GETLIST), mContext);
        message.mApi = AsynHttpClient.API_TALK_LIST;
        message.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execTalkHttp(message);
    }


    private void getMyTalkList(int pageIndex) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        if (TalkListActivity.OTHER_PERSONAL_SPACE.equals(mAction)) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SET_USER_ID, mSetUserId));
        }
        if (isUpDate) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, pageIndex * 10 + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, "1"));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGESIZE, "10"));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_PAGEINDEX, pageIndex + ""));
        }
        GetTalkListMsg message = new GetTalkListMsg(mHandler.obtainMessage(MSG_TALK_GETLIST), mContext);
        message.mApi = AsynHttpClient.API_TALK_SELF;
        message.mParams = nvps;
        AsynHttpClient.getInstance(mContext).execTalkHttp(message);
    }


    /**
     * 是否有这条动态
     *
     * @param talkId
     * @return
     */
    public int getTalkCount(String talkId) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        int count = 0;
        try {
            db = mHelper.getReadableDatabase();
            String[] whereArgs = {talkId, mAction};
            cursor = db.rawQuery("select count(*) from talk_table where talk_id = ? and talk_action = ?", whereArgs);
            cursor.moveToFirst();
            count = cursor.getInt(0);
        } catch (SQLException e) {
            //: handle exception
            Log.e(TAG, "Error getCount: " + e);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return count;
    }


    /**
     * 此方法会对比本地查询的结果和从服务器获取的结果
     * 如果本地不存在，则将获取的结果存入数据库
     * 如果本地已经存在的数据中包含从服务器段获取的，则更新数据库(并删除本地的这个数据)
     * 本地和获取的匹配完毕之后，若本地的变量还有数据，则将剩下的数据从数据库中全部删除
     *
     * @param localTalkList
     * @param cloudTalkList
     * @return
     */
    private boolean updateCloudTalkData(ArrayList<TalkListData> localTalkList, ArrayList<TalkListData> cloudTalkList) {
        boolean needUpdate = false;

        //如果本地没有，则将从服务器获取的插入数据库，成功则返回true
        if (localTalkList.size() == 0) {
            for (int i = 0; i < cloudTalkList.size(); i++) {
                needUpdate |= (insertTalkData(cloudTalkList.get(i)) != 0);
            }
            return needUpdate;
        }
        //如果本地有
        Iterator<TalkListData> i = cloudTalkList.iterator();
        while (i.hasNext()) {
            TalkListData cloudItem = i.next();
            i.remove();
            //如果本地的里面包含从服务器获取的，则将本地里面的删除掉
            TalkListData localItem = removeTalkById(cloudItem.talkId, localTalkList);
            //如果不包含，则添加进数据库
            if (localItem == null) {
                needUpdate |= (insertTalkData(cloudItem) != 0);
                continue;
            }
            //如果包含，且更新时间新于本地的，则更新数据库里的
            if (!cloudItem.updateTime.equals(localItem.updateTime)) {
                needUpdate |= (updateCloudTalkData(cloudItem.talkId, cloudItem) != 0);
                continue;
            }
        }
        //如果服务器获取到的匹配完毕，本地还有的话，则删除数据库中的本地剩下的过时数据
        if (localTalkList.size() > 0) {
            deleteCloudTalkData(localTalkList);
            needUpdate = true;
        }
        return needUpdate;
    }

    private TalkListData removeTalkById(String talkId, ArrayList<TalkListData> localTalkList) {

        for (int i = 0; i < localTalkList.size(); i++) {
            if (localTalkList.get(i).talkId.equals(talkId)) {
                return localTalkList.remove(i);
            }
        }
        return null;
    }

    private void notifyCloudTalkUpdate() {
        mTalkListData = getLocalTalkData();
        if (mListener != null) mListener.onChange(mTalkListData);
    }

    private void notifyAddTalkList() {
        mTalkListData = getLocalTalkData();
        if (mListener != null) mListener.onAddMore(mTalkListData);
    }

}
